package com.doubao.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

// 注释掉 @Component 禁用此过滤器，避免与JwtAuthFilter冲突
// @Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private static final String AUTH_TOKEN_HEADER = "X-Auth-Token";
    private static final String TRACE_ID_HEADER = "X-Trace-Id";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        // 添加请求跟踪ID
        String traceId = UUID.randomUUID().toString();
        exchange = exchange.mutate()
                .request(builder -> builder.header(TRACE_ID_HEADER, traceId))
                .build();

        // 对公开路径跳过认证
        if (isPublicPath(path)) {
            return chain.filter(exchange);
        }

        // 检查是否有认证令牌
        if (!request.getHeaders().containsKey(AUTH_TOKEN_HEADER)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 在实际实现中，这里还需要验证令牌的有效性
        // 这里只是一个简单的示例

        return chain.filter(exchange);
    }

    private boolean isPublicPath(String path) {
        return path.startsWith("/auth/") ||
                path.contains("/public/") ||
                path.equals("/wechat/callback");
    }

    @Override
    public int getOrder() {
        return -95; // 调整优先级，避免与JwtAuthFilter冲突
    }
}